package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.AssemblyManagement;
import com.lgd.factoryattendance.Bean.DebugLog;
import com.lgd.factoryattendance.Bean.FactoryAbnormalIssues;
import com.lgd.factoryattendance.Bean.MachineDebugInfoBean;
import com.lgd.factoryattendance.Bean.ProjectInfoVo;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.WorkHourStatistics;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.NoDoubleClickUtil;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class DebugLogActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "DebugLogActivity";
    Button bt_debugLog, bt_complete_machine;
    TextView tv_name,tv_workTime,tv_offDutyTime,actualTime_TV,tv_writeAllTime,downTime_TV,
            tv_punch_type, tv_punch_project, tv_project_code;
    EditText et_debugContent, et_abnormal_time ,et_problem_note;
    ImageView iv_historyRecord, iv_back, iv_refresh;
    Long userId,projectid,workhourid;
    String userName_str,group_str;
    LinearLayout parent_layout;
    private final List<String> assemblynameList = new ArrayList<>();   // 部装列表
    String clocktype ,androidId;  // 打卡 类型
    String endTime_str = "";  // 结束时间
    LinearLayout layout_electricalDebug,layout_machineDebug,layout_allTime,
            layout_afterTime,layout_selectionTime,downTime_layout, layout_close, layout_debug_type,
            layout_abnormal, layout_abnormalTime, layout_ProblemNote  ;
    View show_view;
    Long userid;
    private ArrayList<MachineDebugInfoBean> machineDebugInfoBeanArrayList = null;
    int type = 1;
    RadioGroup rg_debug_type;
    RadioButton rb_subassembly, rb_machine;
    Spinner sp_abnormal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debug_log);
        init();
        initDate();
    }

    public void init(){
        et_problem_note = findViewById(R.id.et_problem_note);
        et_abnormal_time = findViewById(R.id.et_abnormal_time);
        sp_abnormal = findViewById(R.id.sp_abnormal);
        layout_ProblemNote = findViewById(R.id.layout_ProblemNote);
        layout_abnormalTime = findViewById(R.id.layout_abnormalTime);
        layout_abnormal = findViewById(R.id.layout_abnormal);
        layout_debug_type = findViewById(R.id.layout_debug_type);
        bt_complete_machine = findViewById(R.id.bt_complete_machine);
        bt_complete_machine.setOnClickListener(this);
        iv_refresh = findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        rg_debug_type = findViewById(R.id.rg_debug_type);
        rb_subassembly = findViewById(R.id.rb_subassembly);
        rb_machine = findViewById(R.id.rb_machine);
        androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        tv_punch_type = findViewById(R.id.tv_punch_type);
        tv_punch_project = findViewById(R.id.tv_punch_project);
        tv_project_code = findViewById(R.id.tv_project_code);
        layout_close = findViewById(R.id.layout_close);
        layout_close.setOnClickListener(this);
        downTime_TV = findViewById(R.id.downTime_TV);
        downTime_layout = findViewById(R.id.downTime_layout);
        downTime_layout.setOnClickListener(this);
        layout_selectionTime = findViewById(R.id.layout_selectionTime);
        layout_afterTime = findViewById(R.id.layout_afterTime);
        tv_writeAllTime = findViewById(R.id.tv_writeAllTime);
        et_debugContent = findViewById(R.id.et_debugContent);
        layout_allTime = findViewById(R.id.layout_allTime);
        show_view = findViewById(R.id.show_view);
        layout_machineDebug = findViewById(R.id.layout_machineDebug);
        layout_electricalDebug = findViewById(R.id.layout_electricalDebug);
        tv_workTime = findViewById(R.id.tv_workTime);
        tv_offDutyTime = findViewById(R.id.tv_offDutyTime);
        actualTime_TV = findViewById(R.id.actualTime_TV);
        parent_layout = findViewById(R.id.parent_layout);
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        bt_debugLog = findViewById(R.id.bt_debugLog);
        bt_debugLog.setOnClickListener(this);
        tv_name = findViewById(R.id.tv_name);
        iv_historyRecord = findViewById(R.id.iv_historyRecord);
        iv_historyRecord.setOnClickListener(this);
        setDebugType();
    }
    ArrayAdapter<String> abnormal_adapter;
    public void setAbnormalCause(){
        int inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
        et_abnormal_time.setInputType(inputType);
        et_abnormal_time.setFilters(new InputFilter[]{lengthfilter});
        abnormal_adapter = new ArrayAdapter<>(this,R.layout.spinner_item,abnormalCause_list);
        sp_abnormal.setAdapter(abnormal_adapter);
        sp_abnormal.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String abnormal_str = abnormalCause_list.get(position);
                if (abnormal_str.equals("无异常")){
                    et_abnormal_time.setText("0");
                    et_abnormal_time.setTextColor(Color.parseColor("#000000"));
                    et_problem_note.setText("无异常上报！");
                    et_problem_note.setTextColor(Color.parseColor("#000000"));
                    et_abnormal_time.setEnabled(false);
                    et_problem_note.setEnabled(false);
                }else {
                    et_abnormal_time.setText(null);
                    et_problem_note.setText(null);
                    et_abnormal_time.setEnabled(true);
                    et_problem_note.setEnabled(true);
                }

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

    }

    public void setDebugType (){
        rg_debug_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                String debugType_str = radioButton.getText().toString();
                Log.d(TAG, "onCheckedChanged: -----选中的值----"+debugType_str);
                String actualTimeText = actualTime_TV.getText().toString();
                if (actualTimeText.equals("")){
                    ToastUtils.warnShowLong(getApplicationContext(),"工作时长不为空，请选择时长！！");
                    rb_subassembly.setChecked(true);
                }else {
                    if (debugType_str.equals("整机调试")){

                        layout_electricalDebug.setVisibility(View.VISIBLE);
                        bt_complete_machine.setVisibility(View.VISIBLE);
                        layout_machineDebug.setVisibility(View.GONE);
                        parent_layout.setVisibility(View.GONE);
                        layout_allTime.setVisibility(View.GONE);
                        show_view.setVisibility(View.GONE);
                        bt_debugLog.setVisibility(View.GONE);
                        layout_abnormal.setVisibility(View.VISIBLE);
                        layout_abnormalTime.setVisibility(View.VISIBLE);
                        layout_ProblemNote.setVisibility(View.VISIBLE);
                    }else {
                        layout_machineDebug.setVisibility(View.VISIBLE);
                        parent_layout.setVisibility(View.VISIBLE);
                        layout_allTime.setVisibility(View.VISIBLE);
                        show_view.setVisibility(View.VISIBLE);
                        bt_debugLog.setVisibility(View.VISIBLE);
                        layout_electricalDebug.setVisibility(View.GONE);
                        bt_complete_machine.setVisibility(View.GONE);
                        layout_abnormal.setVisibility(View.GONE);
                        layout_abnormalTime.setVisibility(View.GONE);
                        layout_ProblemNote.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    public void initDate(){
        FactoryAbnormalIssues f = new FactoryAbnormalIssues();
        abnormalCause(f);
        //  上个界面传值
        Intent intent = getIntent();
        userName_str = intent.getStringExtra("userName");
        group_str = intent.getStringExtra("group");
        workhourid = intent.getLongExtra("workhourid",0);
        if (workhourid == 0){
            ToastUtils.warnShowLong(getApplicationContext(),"请打卡后再来");
        }else {
            endTime_str = intent.getStringExtra("endTime");
            if (TextUtils.isEmpty(endTime_str)){
                layout_selectionTime.setVisibility(View.VISIBLE);
                layout_afterTime.setVisibility(View.GONE);
                type = 2;
            }else {
                layout_selectionTime.setVisibility(View.GONE);
                layout_afterTime.setVisibility(View.VISIBLE);
                type = 1;
            }
            WorkHourStatistics w = new WorkHourStatistics();
            w.setWorkhourid(workhourid);
            findWorkHour(w);       //查询 工单 BY workID
        }
    }
    public void setSelectAssemblyById (Long projectId){
        ProjectManagement p = new ProjectManagement();
        p.setProjectid(projectId);
        getSelectAssemblyById(p);
    }

//      页面点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_debugLog:
                if (NoDoubleClickUtil.isFastDoubleClick()){return;}
                switch (clocktype){
                    case "机械调试":
                        if (actualTime_TV.getText().toString().equals("")){
                            ToastUtils.warnShowLong(getApplicationContext(),"请选择您需要补卡的时间！！！");
                        }else {
                            int i = GetViewValue();
                            switch (i){
                                case 0:
                                    Double actualTime = Double.valueOf(actualTime_TV.getText().toString());
                                    if (sum <= actualTime){
                                        System.out.println("-----安全数据-----"+machineDebugInfoBeanArrayList);
                                        setAddDebugLogAndUpdaterWorkHours();
                                    }else {
                                        ToastUtils.warnShowLong(getApplicationContext(),"填报时间大于工作时长，请更改!");
                                        tv_writeAllTime.setText("");
                                    }
                                    break;
                                case 1:
                                    ToastUtils.warnShowLong(getApplicationContext(),"请确保填写内容不为空!");
                                    break;
                                case 2:
                                    ToastUtils.warnShowLong(getApplicationContext(),"异常时间大于填报时长!");
                                    break;
                                case 3:
                                    ToastUtils.warnShowLong(getApplicationContext(),"至少填写一项部装调试信息!");
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    case "电气调试":
                        String actualTime_str = actualTime_TV.getText().toString();
                        String debugContent_str = et_debugContent.getText().toString();
                        String abnormal_type = sp_abnormal.getSelectedItem().toString();
                        String abnormal_time = et_abnormal_time.getText().toString();
                        String problem_note = et_problem_note.getText().toString();
                        if (TextUtils.isEmpty(actualTime_str) || TextUtils.isEmpty(debugContent_str)
                                || abnormal_type.equals("请选择原因") || TextUtils.isEmpty(abnormal_type)
                                || TextUtils.isEmpty(abnormal_time) || TextUtils.isEmpty(problem_note)) {
                            ToastUtils.warnShowLong(getApplicationContext(), "请确保填写内容不为空");
                            return;
                        }
                        if (abnormal_time.length() > 0 && actualTime_str.length() > 0){
                            if (Double.parseDouble(abnormal_time) > Double.parseDouble(actualTime_str)){
                                ToastUtils.warnShowLong(getApplicationContext(),"异常时间大于填报时长！");
                                return;
                            }
                        }
                        // 电气调试
                        DebugLog debugLog_e = new DebugLog();
                        debugLog_e.setProjectid(projectid);
                        debugLog_e.setUserid(userid);
                        debugLog_e.setDebugcontent("( "+"电气调试"+" ) "+debugContent_str);
                        debugLog_e.setDebugDuration(actualTime_str);
                        debugLog_e.setDebugType("电气调试");
                        debugLog_e.setWorkHourId(workhourid);
                        debugLog_e.setAbnormalType(abnormal_type);
                        debugLog_e.setAbnormalTime(abnormal_time);
                        debugLog_e.setAbnormalContent(problem_note);
                        debugLog_e.setWorkHourStatisticsList(setWorkHoursList());

                        getAddDebugLogAndUpdaterWorkHours2(debugLog_e);
                        break;
                }
                break;
            case R.id.iv_historyRecord:
                Intent intent = new Intent(getApplicationContext(),DebugLogHistoryActivity.class);
                intent.putExtra("userId",userid);
                startActivity(intent);
                break;
            case R.id.layout_close:
//                Intent intent2 = new Intent();
//                setResult(Activity.RESULT_OK,intent2);
                finish();
                break;
            case R.id.downTime_layout: // 下班时间选择
                TimeSelect();
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            case R.id.bt_complete_machine:
                if (NoDoubleClickUtil.isFastDoubleClick()){return;}
//                bt_complete_machine.setEnabled(false);
                Log.d(TAG, "onClick: ----- 整机调试上报------");
                String debugContent_str = et_debugContent.getText().toString();        // 调试内容
                String abnormal_type = sp_abnormal.getSelectedItem().toString();      // 异常类型
                String abnormal_time = et_abnormal_time.getText().toString();        // 异常时间
                String problem_note = et_problem_note.getText().toString();         // 异常内容
                String actual_time = actualTime_TV.getText().toString();           // 打卡工作时间
                if (TextUtils.isEmpty(debugContent_str) || TextUtils.isEmpty(abnormal_type) || abnormal_type.equals("请选择原因")
                        || TextUtils.isEmpty(abnormal_time) || TextUtils.isEmpty(problem_note) || TextUtils.isEmpty(actual_time)){
                    ToastUtils.warnShowLong(getApplicationContext(),"请确保填写内容不为空!!");
                    return;
                }
                if (abnormal_time.length() > 0 && actual_time.length() > 0){
                    try {
                        if (Double.parseDouble(abnormal_time) > Double.parseDouble(actual_time)){
                            ToastUtils.warnShowLong(getApplicationContext(),"异常时间大于填报时长！");
                            return;
                        }
                    }catch (NumberFormatException e){
                        ToastUtils.warnShowLong(getApplicationContext(),"异常时间格式错误！");
                        return;
                    }
                }

                DebugLog debugLog_e = new DebugLog();
                debugLog_e.setProjectid(projectid);
                debugLog_e.setUserid(userid);
                debugLog_e.setDebugcontent("( "+"整机调试"+" ) "+debugContent_str);
                debugLog_e.setDebugDuration(actual_time);
                debugLog_e.setDebugType("机械调试");
                debugLog_e.setWorkHourId(workhourid);
                debugLog_e.setWorkHourStatisticsList(setWorkHoursList());
                debugLog_e.setAbnormalType(abnormal_type);
                debugLog_e.setAbnormalTime(abnormal_time);
                debugLog_e.setAbnormalContent(problem_note);

                getAddDebugLogAndUpdaterWorkHours2(debugLog_e);
                break;
            default:
                break;
        }
    }

    public void getSelectAssemblyById (ProjectManagement p){
        API.selectAssemblyById(p, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectInfoVo> projectInfoVoList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectInfoVo>>(){}.getType());
                        Log.d(TAG, "onSuccess: ------huoqushujuu--------"+projectInfoVoList);
                        if (projectInfoVoList.size() > 0){
                            List<AssemblyManagement> assemblyList = projectInfoVoList.get(0).getAssemblyManagementList();
                            if (assemblyList.size() > 0){
                                assemblynameList.clear();
                                for (AssemblyManagement a : assemblyList) {
                                    assemblynameList.add(a.getAssemblyname());
                                }
                            }else {
                                if (clocktype.equals("机械调试")){
                                    ToastUtils.warnShowLong(getApplicationContext(),"当前项目部装为空，请联系管理员添加！");
                                }
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    //  循环 layout 样式  机械调试
    public void forLinearLayout (){
        int marginRightInPx = dpToPx(5);
        int margLeftInPx = dpToPx(5);
        int assSize = assemblynameList.size();
        for (int i = 0; i < assSize; i++) {
            // 创建新的LinearLayout
            LinearLayout newLinearLayout = new LinearLayout(this);
            LinearLayout.LayoutParams newlayoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            newLinearLayout.setOrientation(LinearLayout.VERTICAL);
            newLinearLayout.setBackgroundResource(R.drawable.rounded_background);
            newlayoutParams.setMargins(dpToPx(5),dpToPx(8),dpToPx(5),0);
            newLinearLayout.setLayoutParams(newlayoutParams);

            LinearLayout linearLayout = new LinearLayout(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0,dpToPx(8),5,0);
            linearLayout.setLayoutParams(layoutParams);
            // 创建 部装 TextView
            TextView textView = new TextView(DebugLogActivity.this);
            LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.5f);
            textView.setMinHeight(dpToPx(60));
            textView.setLayoutParams(textViewParams);
            textView.setText("#"+assemblynameList.get(i)+"#");
            textView.setTextColor(getResources().getColor(R.color.deepskyblue));
            textView.setTextSize(20);
            textView.setGravity(Gravity.CENTER);
            linearLayout.addView(textView);
            //  时长 edittext
            EditText editTextDuration = new EditText(this);
            int inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
            editTextDuration.setInputType(inputType);  // 设置输入规则
            // 限制 小数点后一位
            InputFilter lengthfilter = new InputFilter() {
                public CharSequence filter(CharSequence source, int start, int end,
                                           Spanned dest, int dstart, int dend) {
                    // 删除等特殊字符，直接返回
                    if ("".equals(source.toString())) {
                        return null;
                    }
                    String dValue = dest.toString();

                    String sValue = source.toString();
                    if (dValue.length() == 0 && sValue.length() == 1) {
                        if (!Character.isDigit(sValue.charAt(0))) {    // 第一个字符必须是数字
                            return "";
                        }
                    }

                    String[] splitArray = dValue.split("\\.");
                    if (splitArray.length > 1) {
                        String dotValue = splitArray[1];
                        // 限制小数点 后两位  dotValue.length() + 1 - 2 (改变小数点后的值)
                        int diff = dotValue.length() + 1 - 2;
                        if (diff > 0) {
                            return source.subSequence(start, end - diff);
                        }
                    }
                    return null;
                }
            };
            editTextDuration.setFilters(new InputFilter[]{lengthfilter});  // 限制输入内容
            editTextDuration.setHint("请输入时长");
            editTextDuration.setTextSize(18);
            editTextDuration.setGravity(Gravity.CENTER);
            editTextDuration.setBackgroundResource(R.drawable.edittext_border);
            LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
            editTextParams.setMargins(dpToPx(15),0,dpToPx(15),0);
            editTextDuration.setLayoutParams(editTextParams);
            linearLayout.addView(editTextDuration);
            //  调试内容 edittext
            EditText editTextContent = new EditText(this);
            editTextContent.setHint("请输入调试内容");
            editTextContent.setGravity(Gravity.CENTER);
            editTextContent.setTextSize(18);
            editTextContent.setMinHeight(dpToPx(50));
            editTextContent.setBackgroundResource(R.drawable.edittext_border);
            LinearLayout.LayoutParams editTextParams2 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 2f);
            editTextParams2.setMargins(margLeftInPx,0,marginRightInPx,0);
            editTextContent.setLayoutParams(editTextParams2);
            linearLayout.addView(editTextContent);
            // 创建 问题 下拉框 布局
            LinearLayout problemTypeLayout = new LinearLayout(this);
            LinearLayout.LayoutParams problemTypeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            problemTypeLayout.setLayoutParams(problemTypeParams);
            TextView problemType_tv = new TextView(this);
            LinearLayout.LayoutParams problemTypeTextViewParams = new LinearLayout.LayoutParams(
                    0, 50, 1f);
            problemType_tv.setLayoutParams(problemTypeTextViewParams);
            problemType_tv.setText("问题类型:");
            problemType_tv.setTextSize(20);
            problemType_tv.setGravity(Gravity.CENTER);
            problemTypeLayout.addView(problemType_tv);
            Spinner typeSpinner = new Spinner(this);
            ArrayAdapter<String> causeAdapter = new ArrayAdapter<>(this,R.layout.spinner_item,abnormalCause_list);
            typeSpinner.setAdapter(causeAdapter);
            LinearLayout.LayoutParams typeSpinnerParams = new LinearLayout.LayoutParams(
                    0, 50, 3f);
            typeSpinner.setLayoutParams(typeSpinnerParams);
            problemTypeLayout.addView(typeSpinner);

            //  异常时间 输入框
            LinearLayout abnormalTimeLayout = new LinearLayout(this);
            abnormalTimeLayout.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            abnormalTimeLayout.setOrientation(LinearLayout.HORIZONTAL);

            TextView tv_abnormalTime = new TextView(this);
            LinearLayout.LayoutParams timeParams = new LinearLayout.LayoutParams(
                    0, 50, 1f);
            tv_abnormalTime.setLayoutParams(timeParams);
            tv_abnormalTime.setText("异常时间:");
            tv_abnormalTime.setTextSize(20);
            tv_abnormalTime.setGravity(Gravity.CENTER);
            abnormalTimeLayout.addView(tv_abnormalTime);
            // 时长 输入框
            EditText et_time = new EditText(this);
            LinearLayout.LayoutParams editTimeParams = new LinearLayout.LayoutParams(
                    0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
            et_time.setLayoutParams(editTimeParams);
            et_time.setBackgroundResource(R.drawable.edittext_border);
            et_time.setMinHeight(50);
            et_time.setGravity(Gravity.CENTER);
            int inputType2 = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
            et_time.setInputType(inputType2);  // 设置输入规则
            et_time.setFilters(new InputFilter[]{lengthfilter});
            editTimeParams.setMargins(0,dpToPx(10),dpToPx(15),dpToPx(15));
            abnormalTimeLayout.addView(et_time);

            // 创建并添加EditText到newLinearLayout
            LinearLayout editTextLinearLayout = new LinearLayout(this);
            editTextLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            editTextLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

            TextView text_et = new TextView(this);
            LinearLayout.LayoutParams textETParams = new LinearLayout.LayoutParams(
                    0, 50, 1f);
            text_et.setLayoutParams(textETParams);
            text_et.setText("异常描述:");
            text_et.setTextSize(20);
            text_et.setGravity(Gravity.CENTER);
            editTextLinearLayout.addView(text_et);

            //  问题 输入框
            EditText editText = new EditText(this);
            LinearLayout.LayoutParams pro_editTextParams = new LinearLayout.LayoutParams(
                    0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
            editText.setLayoutParams(pro_editTextParams);
            editText.setBackgroundResource(R.drawable.edittext_border);
            editText.setMinHeight(85);
            editText.setGravity(Gravity.CENTER);
            pro_editTextParams.setMargins(0,dpToPx(10),dpToPx(15),dpToPx(15));
            editTextLinearLayout.addView(editText);

            typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String abnormal_str = abnormalCause_list.get(position);
                    if (abnormal_str.equals("无异常")){
                        editText.setText("无异常上报！");
                        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
                        editText.setTextColor(Color.parseColor("#000000"));
                        editText.setEnabled(false);
                        et_time.setText("0");
                        et_time.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
                        Typeface typeface = et_time.getTypeface();
                        typeface = Typeface.DEFAULT_BOLD;
                        et_time.setTypeface(typeface);
                        et_time.setTextColor(Color.parseColor("#000000"));
                        et_time.setEnabled(false);
                    }else {
                        editText.setText(null);
                        editText.setEnabled(true);
                        et_time.setText(null);
                        et_time.setEnabled(true);
                    }
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) { }
            });

            // 将TextView和EditText添加到LinearLayout中
            newLinearLayout.addView(linearLayout);
            newLinearLayout.addView(problemTypeLayout);
            newLinearLayout.addView(abnormalTimeLayout);
            newLinearLayout.addView(editTextLinearLayout);

            // 将LinearLayout添加到容器布局中
            parent_layout.addView(newLinearLayout);
        }
}
    int status;
    Double sum ;
    //   获取循环视图的 内容
    public int GetViewValue (){
        status = 0;
        sum = 0.0;
        ViewGroup parent_layout = findViewById(R.id.parent_layout);
        machineDebugInfoBeanArrayList = new ArrayList<>();
        for (int i = 0; i < parent_layout.getChildCount(); i++) {
            LinearLayout linearLayout = (LinearLayout) parent_layout.getChildAt(i);
            LinearLayout linearLayout1 = (LinearLayout) linearLayout.getChildAt(0);
            LinearLayout problemTypeLayout = (LinearLayout) linearLayout.getChildAt(1);
            LinearLayout abnormalTimeLayout = (LinearLayout) linearLayout.getChildAt(2);
            LinearLayout editTextLinearLayout = (LinearLayout) linearLayout.getChildAt(3);

            // 获取 控件 内容
            TextView textView = (TextView) linearLayout1.getChildAt(0);
            EditText editTextDuration = (EditText) linearLayout1.getChildAt(1);
            EditText editTextContent = (EditText) linearLayout1.getChildAt(2);
            Spinner sp_problemType = (Spinner) problemTypeLayout.getChildAt(1);
            EditText abnormal_time = (EditText) abnormalTimeLayout.getChildAt(1);
            EditText abnormal_content = (EditText) editTextLinearLayout.getChildAt(1);

            String textViewText = textView.getText().toString();
            String durationText = editTextDuration.getText().toString();   // 时长
            String contentText = editTextContent.getText().toString();
            String problemType = sp_problemType.getSelectedItem().toString();
            String abnormalTime = abnormal_time.getText().toString();     // 异常时间
            String abnormalContent = abnormal_content.getText().toString();

            System.out.println("---部装---"+textViewText+"--工作时长---"+durationText +
                    "--调试内容---"+contentText+ "---问题类型---"+problemType+
                    "----异常时间---" +abnormalTime+"---异常描述---"+abnormalContent);

            // 异常时间 <=  时长
            if (durationText.length() != 0){
                try {
                    double duration = Double.parseDouble(durationText);
                    sum = add(sum,duration);
                    if (abnormalTime.length() != 0){
                        double abnormal = Double.parseDouble(abnormalTime);
                        if (duration < abnormal){
                            return status = 2;
                        }
                    }
                }catch (Exception e) {
                    ToastUtils.warnShowLong(getApplicationContext(), "请输入正确的数字!");
                }
            }

            if (isEmptyOrWhitespace(durationText) && contentText.isEmpty() &&
                    "请选择原因".equals(problemType) && isEmptyOrWhitespace(abnormalTime) &&
                    abnormalContent.isEmpty()) {
                status = 0;
            } else if (isEmptyOrWhitespace(durationText) || contentText.isEmpty() ||
                    "请选择原因".equals(problemType) || isEmptyOrWhitespace(abnormalTime) ||
                    abnormalContent.isEmpty()){
                status = 1;
                return status;
            }else {
                machineDebugInfoBeanArrayList.add(new MachineDebugInfoBean(
                        textViewText, durationText, contentText,
                        problemType, abnormalTime, abnormalContent));
                status = 0;
            }
        }
        System.out.println("--- 集合大小 ---"+ machineDebugInfoBeanArrayList.size());
        System.out.println("--- 总时长 ---"+sum);
        tv_writeAllTime.setText(String.valueOf(sum));
        if ( machineDebugInfoBeanArrayList.size() == 0){
            return status = 3;
        }
        return status;
    }

    public void setAddDebugLogAndUpdaterWorkHours(){
        DebugLog d = new DebugLog();
        d.setProjectid(projectid);
        d.setUserid(userid);
        d.setDebugType("机械调试");
        d.setWorkHourId(workhourid);
        d.setMachineDebugInfoBeanList(machineDebugInfoBeanArrayList);
        d.setWorkHourStatisticsList(setWorkHoursList());

        getAddDebugLogAndUpdaterWorkHours(d);
    }
    private final ArrayList<WorkHourStatistics> workHourList = new ArrayList<>();
    public ArrayList<WorkHourStatistics> setWorkHoursList(){
        workHourList.clear();
        String duration_str = actualTime_TV.getText().toString();
        if (type == 1){
            workHourList.add(new WorkHourStatistics(androidId, workhourid, projectid,
                    duration_str, endTime_str));
        }else{
            String downTime_str = downTime_TV.getText().toString();
            workHourList.add(new WorkHourStatistics(androidId, workhourid, projectid,
                    duration_str, downTime_str));
        }
        System.out.println("--- 工单上报数据.... ---"+workHourList);
        return workHourList;
    }

    public void getAddDebugLogAndUpdaterWorkHours(DebugLog debugLog){
        API.AddDebugLogAndUpdaterWorkHours(debugLog, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String s = j.getString("msg");
                        String code = j.getString("code");
                        if ("200".equals(code)){
                            ToastUtils.successShowLong(getApplicationContext(),"上报 成功 ！");
                            startActivity(new Intent(DebugLogActivity.this, HomePageActivity.class));
                            finish();
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),s);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
//                ToastUtils.warnShowLong(getApplicationContext(),"上报失败！");
            }
        });
    }
    public void getAddDebugLogAndUpdaterWorkHours2(DebugLog debugLog){
        API.AddDebugLogAndUpdaterWorkHours2(debugLog, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String s = j.getString("msg");
                        String code = j.getString("code");
                        if ("200".equals(code)){
                            ToastUtils.successShowLong(getApplicationContext(),"上报 成功 ！");
                            startActivity(new Intent(DebugLogActivity.this, HomePageActivity.class));
                            finish();
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(), s);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
//                ToastUtils.warnShowLong(getApplicationContext(),"上报失败！");
            }
        });
    }
    private boolean isEmptyOrWhitespace(String str) {
        return str == null || str.trim().isEmpty();
    }
    //  两个 double 相加精度丢失 问题
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    //  上报 调试日志信息
    boolean trueOrFalse;
//    public void ReportDebug (){
//        trueOrFalse = false;
//        if (machineDebugInfoBeanArrayList.size() > 0){
//            for (int i = 0; i < machineDebugInfoBeanArrayList.size(); i++) {   // 机械调试批量上报
//                String debugContent_str = machineDebugInfoBeanArrayList.get(i).getDebugContent();
//                String partType_str = machineDebugInfoBeanArrayList.get(i).getPartType();
//                DebugLog debugLog_m = new DebugLog();
//                debugLog_m.setProjectid(projectid);
//                debugLog_m.setUserid(userid);
//                debugLog_m.setDebugType("机械调试");
//                debugLog_m.setDebugcontent("( "+partType_str+" ) "+debugContent_str);
//                debugLog_m.setWorkHourId(workhourid);           //  添加 工时id
//                debugLog_m.setDebugDuration(machineDebugInfoBeanArrayList.get(i).getDebugDuration());
////                addDebugLog(debugLog_m);
//            }
//            trueOrFalse = true;
//        }else {
//            ToastUtils.warnShowLong(getApplicationContext(),"至少填报一项部装信息");
//            trueOrFalse = false;
//        }
//    }
    // 根据 workid 。。。。
    public void findWorkHour(WorkHourStatistics workHourStatistics){
        API.clockInStatus(workHourStatistics, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                Log.v("----工单信息-----", String.valueOf(workHourList));
                if (workHourList.size() > 0){
                    DebugLogActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_workTime.setText(workHourList.get(0).getStarttime());
                            tv_offDutyTime.setText(endTime_str);
                            tv_name.setText(workHourList.get(0).getNickName());
                            tv_punch_type.setText(workHourList.get(0).getClocktype());
                            tv_punch_project.setText(workHourList.get(0).getProjectName());
                            tv_project_code.setText(workHourList.get(0).getProductAcode());
                            clocktype = workHourList.get(0).getClocktype();
                            projectid = workHourList.get(0).getProjectId();
                            setSelectAssemblyById(projectid);
                            switch (clocktype){
                                case "机械调试":
                                    layout_machineDebug.setVisibility(View.VISIBLE);
                                    parent_layout.setVisibility(View.VISIBLE);
                                    layout_allTime.setVisibility(View.VISIBLE);
                                    show_view.setVisibility(View.VISIBLE);
                                    layout_debug_type.setVisibility(View.VISIBLE);
                                    layout_electricalDebug.setVisibility(View.GONE);
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            forLinearLayout();
                                        }
                                    },888);
                                    break;
                                case "电气调试":
                                    layout_electricalDebug.setVisibility(View.VISIBLE);
                                    layout_machineDebug.setVisibility(View.GONE);
                                    parent_layout.setVisibility(View.GONE);
                                    layout_allTime.setVisibility(View.GONE);
                                    show_view.setVisibility(View.GONE);
                                    layout_debug_type.setVisibility(View.GONE);
                                    layout_abnormal.setVisibility(View.VISIBLE);
                                    layout_abnormalTime.setVisibility(View.VISIBLE);
                                    layout_ProblemNote.setVisibility(View.VISIBLE);
                                    break;
                                default:
                                    break;
                            }
                            //  判断 工单是否已完成
                            if (workHourList.get(0).getStatus().equals("已下班")){
                                ToastUtils.warnShowLong(getApplicationContext(),"该工单已完成!");
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        startActivity( new Intent(DebugLogActivity.this, HomePageActivity.class));
                                        finish();
                                    }
                                },500);
                            }
                        }
                    });
                    userid = workHourList.get(0).getUserid();
                    WorkHourStatistics w = new WorkHourStatistics();
                    w.setStarttime(workHourList.get(0).getStarttime());
                    w.setUserid(userid);
                    w.setEndtime(endTime_str);
                    calculateDuration(w);      //计算时长
                }
            }
            @Override
            public void onFail(int statusCode) {
//                ToastUtils.warnShowLong(getApplicationContext(),"获取工单信息失败");
            }
        });
    }

    boolean addDebugLogStatus ;
    public void addDebugLog(DebugLog debugLog){
        addDebugLogStatus = false;
        API.addDebugLog(debugLog, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(result+"---.......------");
                        JSONObject j = JSONObject.parseObject(result);
                        String s = j.getString("msg");
                        if (s.equals("操作成功")){
                            addDebugLogStatus = true;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    boolean updateWorkHourStatus ;
    // 修改 工单信息
    public void updateWorkHourStatistics(WorkHourStatistics w){
        API.updateWorkHourStatistics(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                System.out.println("-- 修改gggg---"+result);
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String msg = j.getString("msg");
                        switch (msg){
                            case "操作成功":
//                        updateWorkHourStatus = true;
                                ToastUtils.successShowLong(getApplicationContext(),"调试上报操作成功！");
//                                startActivity(new Intent(DebugLogActivity.this,HomePageActivity.class));
//                                finish();
                                Intent intent = new Intent(DebugLogActivity.this,HomePageActivity.class);
                                setResult(Activity.RESULT_OK,intent);
                                finish();
                                break;
                            case "已下班":
                                ToastUtils.warnShowLong(getApplicationContext(),"该工单已打下班卡，无法重复修改");
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public List<String> abnormalCause_list = new ArrayList<>();
    //  异常原因
    public void abnormalCause(FactoryAbnormalIssues f){
        abnormalCause_list.clear();
        API.abnormalCause(f, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<FactoryAbnormalIssues> factoryAbnormalIssuesList = new Gson().fromJson(j.getString("data"), new TypeToken<List<FactoryAbnormalIssues>>(){}.getType());
                        abnormalCause_list.add("请选择原因");
                        if (factoryAbnormalIssuesList != null && !factoryAbnormalIssuesList.isEmpty()){
                            for (int i = 0; i < factoryAbnormalIssuesList.size(); i++) {
                                abnormalCause_list.add(factoryAbnormalIssuesList.get(i).getAbnormalissues());
                            }
                        }
                        setAbnormalCause();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    //  根据开始 + 结束 + useid 查询工时
    public void calculateDuration(WorkHourStatistics w){
        API.calculateDuration(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                DebugLogActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        Log.v("实际工时",result);
                        String actualTime_str = jsonObject.getString("msg");
                        actualTime_TV.setText(actualTime_str);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    private void reStartActivity() {   // 刷新 当前Activity
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (assemblynameList.size() > 0){
            assemblynameList.clear();
        }
    }
    StringBuilder sb = new StringBuilder();
    // 时间 选择器 自定义
    public void TimeSelect (){
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);  // 小时
        int minute = calendar.get(Calendar.MINUTE);     // 分钟
        new TimePickerDialog(DebugLogActivity.this, AlertDialog.THEME_HOLO_LIGHT,new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                actualTime_TV.setText("");
                String formattedTime = formatTime(hourOfDay, minute);
                System.out.println("---  时间 ---" + formattedTime);
                sb.setLength(0);
                SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                // 解析日期时间字符串
                Date dateTimeObj = null;
                try {
                    dateTimeObj = dateTimeFormat.parse(tv_workTime.getText().toString());
                    // 提取日期部分并格式化为字符串
                    String dateStr = dateFormat.format(dateTimeObj);
                    System.out.println(dateStr);
                    sb.append(dateStr).append(" ").append(formattedTime).append(":00");
                    boolean  i = getTimeCompareSize(tv_workTime.getText().toString(),sb.toString());
                    System.out.println(i+"----- 时间比较-----");
                    if (!i){
                        downTime_TV.setText(sb);
                        WorkHourStatistics w = new WorkHourStatistics();
                        w.setStarttime(tv_workTime.getText().toString());
                        w.setUserid(userid);
                        w.setEndtime(downTime_TV.getText().toString());
                        calculateDuration(w);
                    }else {
                        ToastUtils.warnShowLong(getApplicationContext(),"选择时间小于开始时间，请重新选择!!");
                        downTime_TV.setText("请重新选择");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        },hour,minute,true).show();
    }

    // 时间 格式转化
    private String formatTime(int hourOfDay, int minute) {
        // 使用String.format来格式化时间
        return String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
    }
    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
//    dp  转化为  像素
    public int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }
    /**
     * 对比两个时间
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean getTimeCompareSize(String startTime, String endTime) {
        int i = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //正常情况下的逻辑操作.
                i = 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (i == 1 || i == 2) {
            return true;
        } else {
            return false;
        }
    }
    InputFilter lengthfilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String dValue = dest.toString();


            String sValue = source.toString();
            // 检查是否是第一个字符输入
            if (dValue.length() == 0 && sValue.length() == 1) {
                // 第一个字符必须是数字
                if (!Character.isDigit(sValue.charAt(0))) {
                    return ""; // 返回空字符串表示拒绝该输入
                }
            }


            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - 2;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };

}